package com.powernode.ssm.consumer;

import com.powernode.ssm.config.RabbitMQConfig;
import com.powernode.ssm.pojo.bo.EmaiNotificationMessage;
import com.powernode.ssm.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
@Component
public class EmailNotificationConsumer {

    @Autowired
    MailService mailService;

    /**
     * 监听邮件通知队列
     */
    @RabbitListener(queues = RabbitMQConfig.EMAIL_NOTIFICATION_QUEUE)
    public void processLoginNotification(EmaiNotificationMessage message) {
        try {
            String username = message.getUsername();
            String emailAddress = message.getEmailAddress();
            LocalDateTime loginTime = message.getLoginTime();

            log.info("收到登录通知任务 -> 用户: {}, 邮箱: {}, 登录时间: {}",
                    username, emailAddress, loginTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

            // TODO：调用邮件服务，真正发送邮件
            sendLoginSuccessEmail(emailAddress, username, loginTime);

            log.info("登录成功邮件已发送至: {}", emailAddress);

        } catch (Exception e) {
            log.error("处理登录通知失败", e);
        }
    }

    /**
     * 模拟/实际调用邮件服务发送登录成功邮件
     */
    private void sendLoginSuccessEmail(String toEmail, String username, LocalDateTime loginTime) {
        // 这里你可以调用你项目中的 MailService，例如：
         mailService.sendSimpleMail(toEmail, "登录成功通知", "用户 " + username + " 于 " + loginTime + " 登录系统");

        // 暂时打印模拟发送
//        System.out.println("[邮件服务] 向邮箱 " + toEmail + " 发送登录成功通知：用户 " + username + " 于 " +
//                loginTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + " 登录系统");
    }
}